1689C - Infected Tree - CodeForces Solution


dfs and similar dp trees *1600

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;
 
vector<vector<int>> g(300005);
int ch[300005],dp[300005];
 
void dfs(int p, int q)
{
    ch[p]=1,dp[p]=0; int s=0;
    for (auto it : g[p]) if (it!=q)
    {
        dfs(it,p); s+=dp[it];
        ch[p]+=ch[it];
    }
    for (auto it : g[p]) if (it!=q)
    {
        dp[p]=max(dp[p],s-dp[it]+ch[it]-1);
    }
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
 
    int t; cin>>t;
    while (t--)
    {
        int n; cin>>n;
        for (int i=1;i<=n;i++) g[i].clear();
        for (int i=1;i<n;i++)
        {
            int u,v; cin>>u>>v;
            g[u].push_back(v);
            g[v].push_back(u);
        }
 
        dfs(1,0);
        cout<<dp[1]<<"\n";
    }
}


Comments

Submit
0 Comments
More Questions

3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret